In Python, if-else is a conditional statement that executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed. The if-else statement is a fundamental part of Python and most programming languages.
Here’s a basic structure of an if-else statement in Python:
Syntax
if else syntax
if condition:
# block of code to execute if the condition is true
else:
# block of code to execute if the condition is false
Let’s break it down:
⯌
if keyword: This keyword is used to define the if statement.
⯌
condition: This is a statement that returns either True or False. Python will execute the block of code under if only if this condition is True.
⯌
: (colon): The colon is used to denote the start of a block of code.
⯌
else keyword: This keyword is used to define a block of code that will be executed if the if condition is False.
⯌
Indentation: Python uses indentation to define blocks of code. The code within the if and else blocks should be indented.
Here’s an example:
Python if else basic examples
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
Output
x is greater than 5
In this example, since x is 10 which is greater than 5, the output will be "x is greater than 5".
Remember, the else clause is optional. If it’s omitted, Python will simply do nothing if the condition is False.
More examples:
Checking if a number is positive or negative
python if else example - positive or negative number
num = -5
if num >= 0:
print("Number is positive")
else:
print("Number is negative")
Output
Number is negative
Checking if a number is even or odd
Odd or even example using python if else condition
num = 7
if num % 2 == 0:
print("Number is even")
else:
print("Number is odd")
Output
Number is odd
Checking if a year is a leap year
Leap year example in python using if else statement
year = 2024
if year % 4 == 0:
if year % 100 != 0 or year % 400 == 0:
print("Leap year")
else:
print("Not a leap year")
else:
print("Not a leap year")
Output
Leap year
Checking if a student has passed or failed
python if else example - pass or fail in exam
score = 85
if score >= 60:
print("Passed")
else:
print("Failed")
Output
Passed
Checking if a character is a vowel or consonant
python if else example - checking vowel or consonant
char = 'a'
if char in 'aeiou':
print("Vowel")
else:
print("Consonant")
Output
Vowel